package com.gxa.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxa.config.RabbitConfig;
import com.gxa.dto.MsgDTO;
import com.gxa.service.SendMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RabbitMsgListener {

    final SendMessageService sendMessageService;

    public RabbitMsgListener(SendMessageService sendMessageService) {
        this.sendMessageService = sendMessageService;
    }

    @RabbitListener(bindings = {
            //@QueueBinding注解要完成队列和交换机的
            @QueueBinding(
                    //@Queue创建一个队列（没有指定参数则表示创建一个随机队列）
                    value = @Queue(),
                    //创建一个交换机
                    exchange = @Exchange(name = RabbitConfig.FANOUT_EXCHANGE, type = "fanout"))})
    public void fanoutReceive(String msg) {
        JSONObject object = JSON.parseObject(msg);
        MsgDTO msgDTO = JSON.toJavaObject(object, MsgDTO.class);
        sendMessageService.sendToUser(msgDTO);
        log.info("{}", "监听并推送消息");
    }
}

